<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Restful Example--User Management</title>

<jsp:include page="../header.jsp"><jsp:param name="groups" value="jquery,jquery-ui,jqgrid,validation,common"/></jsp:include>

<script type="text/javascript">
	$(document).ready(function(){

		var inputDialog = $("#inputDialog");
		var resultList = $("#resultList");
		var inputForm = $("#inputForm");
		var searchForm = $("#searchForm");

		var queryUrl = 'UserAction/query.do';
		var getUrl = 'UserAction/get.do';
		var getVersionUrl = 'UserAction/getVersion.do';
		var saveUrl = 'UserAction/save.do';
		var updateUrl = 'UserAction/update.do';
		var deleteUrl = 'UserAction/delete.do';
		
		//To indicate the open user input dailog is new creation or not. 
		var isNew = true;
		var girdColumns;
		
		var version = 'unkown';
		$.ajax({
			   url: getVersionUrl,
			   dataType: 'text',
			   async: false,
			   success: function(result){
				   version = result;
			   }
		});
		
		if(version == '1') {
			$('.part_v2').hide();
			$('.part_v2 input').prop('disabled', true);
			girdColumns = [ 
							{name:'username', label:'Username', width:80, sortable:true},
							{name:'name', label:'Name', width:80, sortable:false},
							{name:'email', label:'E-Mail', width:90, sortable:false}];
			
		}
		else if(version == '2') {
			$('.part_v2').show();
			$('.part_v2 input').prop('disabled', false);
			girdColumns = [ 
							{name:'username', label:'Username', width:90, sortable:true},
							{name:'name', label:'Name', width:80, sortable:false},
							{name:'email', label:'E-Mail', width:90, sortable:false},
							{name:'birthday', label:'birthday', width:80, sortable:false},
							{name:'phone', label:'phone', width:80, sortable:false},
							{name:'mobile', label:'mobile', width:80, sortable:false}
							];
		}
		else {
			alert('System error, can not find the correct version of party module!');
		}
		
		$( 'input[name="user.birthday"]', inputForm).datepicker({
			showOn: "button", buttonImage: "../images/calendar.gif",
			buttonImageOnly: true, changeMonth: true, changeYear: true,showButtonPanel: true
		});
		
		var validator = inputForm.validate({
			 rules:{
	              "user.username":{required:true, minlength:3},
	              "user.password":{required:true, minlength:3},
	              "user.name":{required:true, minlength:3},
	              "user.email":{required:true, email:true}
	         }
	    });

		inputDialog.dialog({
			buttons: {
				'Save': doSave,
				'Close': function() { $(this).dialog('close'); }
			},
			beforeClose: function(event, ui) { 
				validator.resetForm(); //After dialog closed, clean the validation error style and prompt text.
				inputForm.resetForm();
			}
		});
		 
		
		resultList.jqGrid({
			datatype: 'local',
			ajaxGridOptions: {type:"POST"},
			jsonReader: {repeatitems: false},
			prmNames: {page:"queryParam.page", rows:"queryParam.rows", sort:"queryParam.sort", order: "queryParam.order"},
			height: "100%",
			rowNum: 10,
			rowList:[10,20,30],
			autowidth: true,
			multiselect: true,
			viewrecords: true,
			url:queryUrl, 
			colModel: girdColumns,
			pager: $("#resultPager"),
			sortname: 'userId',
			sortorder: "desc"
		});
		
		$('button.onSearch').click(reloadSearch);
		
		$('#toolbar button.onNew').click(function (){
			isNew = true;
			$('input[name="user.username"]', inputDialog).prop('readonly', false);
			inputDialog.dialog('open');
		});
		
		$('#toolbar button.onModify').click(function (){
			isNew = false;
			var rowId = resultList.jqGrid('getGridParam','selrow');
			if(rowId != null) {
				var username = resultList.jqGrid('getCell', rowId, 'username');
	            var queryString = 'user.username=' + encodeURIComponent(username);
				$.ajax({
					   url: getUrl,
					   data: queryString,
					   success: function(result){
							inputForm.deserialize(result, {inputPrefix:'user.'});
					   }
				});
				
				//disable username property, because it is key, could not be modified!
				$('input[name="user.username"]', inputDialog).prop('readonly', true);
				inputDialog.dialog('open');
			}
			else {
				$.msgBox('warn', '', 'Please select one row to modify!');
				return false;
			}
		});
		
		$('#toolbar button.onDelete').click(function () {
			var ids = resultList.jqGrid('getGridParam','selarrrow');

			if(ids.length>0){
				$.msgBox('confirm', 'Confirmation', 
					'Do you want to delete selected items?', 
					function(result) { 
						if(result == true) {
						 	var queryString = '';
				        	for(i=0;i<ids.length;i++){
				        		var username = resultList.jqGrid('getCell', ids[i], 'username');
				        		queryString += ((i==0) ? '' : '&') + 'delUsernames=' + username;
							}
							
							$.ajax({
								   url: deleteUrl,
								   data: queryString,
								   success: function(result) {
								   		$.msgBox('info', '', result.message);
								   		reloadSearch();
								   }
							});
						}
					});
			}
			else {
				$.msgBox('warn', '', 'Please select at least one row to delete!');
				return false;
			} 
		});
		
		function reloadSearch(){
			var postData = searchForm.serializeJqgrid();
			resultList.setGridParam({datatype:'json', postData:postData, page:1}).trigger("reloadGrid");
			return false;
		}
		
		function doSave() {
			if(!validator.form()) { 
		         validator.focusInvalid();
		         return false;
		    }
			
			var postData = inputForm.serialize();
			
			$.ajax({
				   url: (isNew) ? saveUrl : updateUrl,
				   data: postData,
				   success: function(result){
						$.msgBox('info', '', result.message, function() { 
							inputDialog.dialog('close');
							reloadSearch();
						});
				   }
			});
		}
		
		jqgridAutoResize(resultList);
		
		$('button').button();
		
		reloadSearch();
		
	});

</script>

</head>
<body>
<center>
<div class="contentArea">
	<form id="searchForm">
	<table width="100%" align="center" class="ui-widget ui-widget-content">
		<thead>
			<tr class="ui-widget-header">
				<td colspan="4">Query</td>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>Username: </td>
				<td><input type="text" name="queryParam.username"/></td>
				<td>E-Mail: </td>
				<td><input type="text" name="queryParam.email"/></td>
			</tr>
		</tbody>
		<tfoot>
			<tr><td colspan="4" align="center">
				<button class="onSearch">Go Search</button>
			</td></tr>
		</tfoot>
	</table>
	</form>
	<br/>
	<div id="toolbar" style="text-align:left;">
		<button class="onNew">New</button>
		<button class="onModify">Modify</button>
		<button class="onDelete">Delete</button>
	</div>
	<table id="resultList"></table>
	<div id="resultPager" style="text-align:center;"></div>
	
	<div align="center" id="inputDialog" title="User Informations">
	   	<form id="inputForm">
	   		<table width="100%">
	   			<tbody>
				<tr>
				  <td width="120">Username: </td>
				  <td><input name="user.username" type="text"/></td>
				</tr>
				<tr>
				  <td>Password: </td>
				  <td><input name="user.password" type="text"/></td>
				</tr>
				<tr>
				  <td>Name: </td>
				  <td><input name="user.name" type="text" /></td>
				</tr>
				<tr>
				  <td>E-Mail:</td>
				  <td><input name="user.email" type="text" /></td>
				</tr>
				<tr class="part_v2">
				  <td>Birthday: </td>
				  <td><input name="user.birthday" type="text"/></td>
				</tr>
				<tr class="part_v2">
				  <td>Phone: </td>
				  <td><input name="user.phone" type="text" /></td>
				</tr>
				<tr class="part_v2">
				  <td>Mobile:</td>
				  <td><input name="user.mobile" type="text" /></td>
				</tr>
				</tbody>
	   		</table>
	   	</form>
	</div>
</div>
</center>
</body>
</html>

	